package com.example.bbs.web.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "RefreshCodeServlet", value = "/doRefreshCode")
public class RefreshCodeServlet extends HttpServlet {
    private List<String> list;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //随机生成4位数字+字母验证码
        String code = "";
        for (int i = 0; i < 4; i++) {
            int index = (int)(Math.random() * list.size());
            code = code.concat(list.get(index));
        }
        //保存到session
        request.getSession().setAttribute("code",code);

        //Java2D
        //创建图片
        BufferedImage img = new BufferedImage(66,36,
                BufferedImage.TYPE_INT_RGB);
        //获取图形对象
        Graphics2D g2 = (Graphics2D)img.getGraphics();
        //白底
        g2.setColor(Color.WHITE);
        //填充
        g2.fillRect(0,0,img.getWidth(),img.getHeight());
        //设置画笔颜色
        g2.setColor(Color.BLACK);
        //设置字体
        g2.setFont(new Font("宋体",Font.PLAIN,24));
        //将验证码画到图片上
        g2.drawString(code,0,25);
        //画干扰
        g2.setColor(Color.BLUE);
        g2.drawLine(0,0,img.getWidth(),img.getHeight());
        g2.drawLine(0,img.getHeight(),img.getWidth(),0);
        //将图片返回给客户端
        ImageIO.write(img,"jpg",response.getOutputStream());

    }
    @Override
    public void init() throws ServletException {
        //创建随机数池
        list = new ArrayList<>();
        //数字区间
        for (int i = 0; i < 9; i++) {
            list.add(""+i);
        }
        //字母
        for(int i = 'a'; i < 'z'; i++){
            if(i == 'i' || i == 'o' || i == 'l' || i == 'z'){
                continue;
            }
            String str = ((char)i)+"";
            list.add(str);
            list.add(str.toUpperCase());
        }
    }

}
